<template>
  <div style="width:960px">
    <canvas :id="pdfId + '_' + i" v-for="i in numPages"></canvas>
  </div>
</template>

<script>
var pdfjsLib = require('pdfjs-dist/webpack');

export default {
  name: "example-pdfjs",
  data() {
    return {
      pdfId: "pdfId_" + Math.random().toString().replace("0."),
      numPages: 1,
    }
  },
  methods: {
    renderPdf() {
      let width = 960;
      let loadingTask = pdfjsLib.getDocument("./mock/assets/HTML5.Canvas.教程.pdf");
      loadingTask.promise.then(async (pdfDocument) => {
        this.numPages = pdfDocument.numPages;

        for (let i = 1; i <= this.numPages; i++) {
          await pdfDocument.getPage(i).then((pdfPage) => {
            // Display page on the existing canvas with 100% scale.
            let viewport = pdfPage.getViewport(1.0);
            let canvas = document.getElementById(this.pdfId + '_' + i);
            canvas.width = width;
            canvas.height = width / viewport.width * viewport.height;
            let ctx = canvas.getContext('2d');
            let renderTask = pdfPage.render({
              canvasContext: ctx,
              viewport: pdfPage.getViewport(width / viewport.width)
            });
            return renderTask.promise;
          });

          const canvas = document.getElementById(this.pdfId + '_' + i);
          this.addMark(canvas);
        }
      }).catch((ex) => {
        console.error(ex);
      });
    },
    addMark(canvas) {
      let ctx = canvas.getContext('2d'),
        doWidth = canvas.width,
        doHeight = canvas.height;
      ctx.font = "italic small-caps 32px arial";
      //设置字体填充颜色
      ctx.fillStyle = "rgba(220,220,220, .6)";
      //向上旋转5度
      ctx.rotate(-5 * Math.PI / 180);
      //从坐标点(50,50)开始绘制文字
      let name = "样稿";
      //var heightcount = Math.floor(doHeight / 10);
      //var widthcount = Math.floor(doWidth / 8);
      for (let j = -200; j < doHeight; j = j + 200) {
        for (let i = -200; i < doWidth; i = i + 200) {
          ctx.fillText(name, i, j);
        }
      }
    },
    forbidCopy() {
      const el = this.$el;
      el.oncontextmenu = function () { return false };
      el.ondragstart = function () { return false };
      el.onselectstart = function () { return false };
      el.onselect = function () { document.selection.empty(); };
      el.oncopy = function () { document.selection.empty(); };
      el.onbeforecopy = function () { return false; };
      el.onkeydown = function () {
        if ((event.ctrlKey) && (window.event.keycode == 67)) {
          event.returnValue = false;
        }
      }
    }
  },
  created() {

  },
  mounted() {
    this.renderPdf();
    this.forbidCopy();
  }
}
</script>

<style lang="less" scoped>

</style>
